package com.litxuf.logic.core;

import java.util.Locale;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 
 * @author Chen Jun
 * @version 1.0
 */
public class ApplicationContextUtil implements ApplicationContextAware {
	private static ApplicationContext appContext = null;
	private static ApplicationContextUtil context = new ApplicationContextUtil();

	protected ApplicationContextUtil() {
		 
	}

	public static ApplicationContextUtil getContext() {
		if (appContext == null) {
			init(new String[] { "applicationContext.xml"});
		}
		return context;
	}

	/**
	 * @link
	 * @shapeType PatternLink
	 * @pattern Singleton
	 * @supplierRole Singleton factory
	 */


	 

	public Object getBean(String id, Class clazz) {
		return appContext.getBean(id, clazz);
	}

	public String getMessage(String key, Object[] paras, Locale locale) {
		try {
			return appContext.getMessage(key, paras, locale);
		} catch (NoSuchMessageException ex) {
			return ex.getMessage();
		}
	}

	public String getMessage(String key, Object[] paras, String defaultMessage,
			Locale locale) {
		try {
			return appContext.getMessage(key, paras, defaultMessage, locale);
		} catch (Exception ex) {
			return ex.getMessage();
		}
	}

	/**
	 * 应该在程序的起点调用,应该在web应用装载时调用
	 * 
	 * @param saCxt
	 *            ApplicationContext
	 */
	public static void init(ApplicationContext saCxt) {
		if (saCxt != null) {
			appContext = saCxt;
		} else {
			init(new String[] { "applicationContext.xml" });
		}
	}

	/**
	 * 应该在程序的起点调用，如main函数中
	 * 
	 * @param saCxt
	 *            ApplicationContext
	 */
	public static void init(String[] configFiles) {
		try
		{
		if (configFiles != null && configFiles.length > 0) {
			appContext = new ClassPathXmlApplicationContext(configFiles);
		} else {
			appContext = new ClassPathXmlApplicationContext(
					new String[] { "applicationContext.xml" });
		}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		appContext = applicationContext;

	}
}
